import React, { useState, useEffect } from 'react'
import "./LayersManagePanel.css";
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faAngleDoubleRight, faAngleDoubleLeft, faChevronRight, faChevronLeft } from '@fortawesome/free-solid-svg-icons';

import LayerCellXyzWms from "../components/LayerCellXyzWms"
import LayerCellGeneral from '../components/LayerCellGeneral';


//props.onLayerCellSDUIClickedCallback
//props.onLayerCellExportClick(props.lyrParams)}
// props.onLayerCellStatisticClick(props.lyrParams)}
// props.onLayerCellCompositeClick(props.lyrParams)}
// props.onLayerCellSerialClick(props.lyrParams)}
// props.isActiveGroupA  true|false
// props.onIsActiveGroupASetting(true|false)
// props.onLayerCellScriptClick(lyrParams)
// props.onLayerCellOmcClick(lyrParams)
// props.appDateA
// props.appDateB
function LayersManagePanel(props) {
    const [isCompare, setIsCompare] = useState(false);
    const [currentGroup, setCurrentGroup] = useState(props.groupA);
    const [tempOrderedArr, setTempOrderedArr] = useState([]);
    const [isHidePanel, setIsHidePanel] = useState(false);

    //添加图层数组更新的钩子函数，添加图层后App更新GroupA或GroupB，然后调用这个钩子函数，刷新当前图层列表
    useEffect(() => {
        let tempArr = null;
        if (props.isActiveGroupA) {
            setCurrentGroup(props.groupA);
            tempArr = props.groupA;
        }
        else {
            setCurrentGroup(props.groupB);
            tempArr = props.groupB;
        }
        setTempOrderedArr(helperSortArrayOrderByZIndex(tempArr));
        return () => {
        }
    }, [props.groupA, props.groupB, props.isActiveGroupA, isCompare])


    let onStartCompareClicked = function () {

        props.onIsActiveGroupASetting(true);

        setCurrentGroup(props.groupA);
        setIsCompare(true);
        props.onStartCompareClicked();
    }

    let onStopCompareClicked = function () {

        props.onIsActiveGroupASetting(true);

        setCurrentGroup(props.groupA);
        setIsCompare(false);
        props.onStopCompareClicked();
    }

    let onGroupAClicked = function () {

        props.onIsActiveGroupASetting(true);

        setCurrentGroup(props.groupA);
    }

    let onGroupBClicked = function () {

        props.onIsActiveGroupASetting(false);
        setCurrentGroup(props.groupB);
    }

    let onAddLayerClicked = function () {
        props.onAddLayerClicked(props.isActiveGroupA);
    }



    const onDragEndCallback = function (result) {
        if (!result.destination) {
            return;
        }
        const sourceZIndex = tempOrderedArr[result.source.index].zindex;
        const targetZIndex = tempOrderedArr[result.destination.index].zindex;
        const newOrder = helperReorderFunction(currentGroup, sourceZIndex, targetZIndex);
        setTempOrderedArr(helperSortArrayOrderByZIndex(newOrder));
        props.onLayerOrderChanged(props.isActiveGroupA, sourceZIndex, targetZIndex);
    }



    // helperMaxZIndexUnusedIndex 找到temp_order_used为false的最大zindex的索引值
    // 每个对象必须具有 zindex 和 temp_used 两个属性
    const helperMaxZIndexUnusedIndex = function (arr) {
        let maxzindex = -9999;
        let resultIndex = -1;
        for (let i = 0; i < arr.length; ++i) {
            if (arr[i].temp_used == false) {
                if (resultIndex === -1) {
                    resultIndex = i;
                    maxzindex = arr[i].zindex;
                } else if (arr[i].zindex >= maxzindex) {
                    resultIndex = i;
                    maxzindex = arr[i].zindex;
                }
            }
        }
        return resultIndex;
    }

    // 按 zindex 重新排序 值越大越放在上面
    const helperSortArrayOrderByZIndex = function (arr) {
        let tarr1 = [...arr];
        for (let i = 0; i < tarr1.length; ++i) {
            tarr1[i].temp_used = false;
        }
        let resultArr = [];
        for (let i = 0; i < tarr1.length; ++i) {
            const theIndex = helperMaxZIndexUnusedIndex(tarr1);
            resultArr.push(arr[theIndex]);
            tarr1[theIndex].temp_used = true;
        }
        return resultArr;
    }

    //重新排序函数
    const helperReorderFunction = function (arr, sourceZIndex, destinationZIndex) {
        if (arr.length <= 1) {
            return [...arr];
        } else {
            let resultArr = [...arr];
            for (let i = 0; i < resultArr.length; ++i) {
                if (sourceZIndex < destinationZIndex) {//rise
                    if (resultArr[i].zindex >= sourceZIndex && resultArr[i].zindex <= destinationZIndex) {
                        let newOne = { ...resultArr[i] };
                        if (resultArr[i].zindex == sourceZIndex) {
                            newOne.zindex = destinationZIndex;
                        } else {
                            newOne.zindex = resultArr[i].zindex - 1;
                        }
                        resultArr[i] = newOne;
                    }
                } else {
                    //downside
                    if (resultArr[i].zindex >= destinationZIndex && resultArr[i].zindex <= sourceZIndex) {
                        let newOne = { ...resultArr[i] };
                        if (resultArr[i].zindex == sourceZIndex) {
                            newOne.zindex = destinationZIndex;
                        } else {
                            newOne.zindex = resultArr[i].zindex + 1;
                        }
                        resultArr[i] = newOne;
                    }
                }
            }
            return resultArr;
        }
    }

    //图层是否可见切换回调
    const onLayerCellToggleLayerVisibleCallback = function (displayid) {
        props.onToggleLayerVisible(props.isActiveGroupA, displayid);
    }

    //图层关闭按钮点击回调
    const onLayerCellCloseButtonClickedCallback = function (displayid) {
        props.onLayerCellCloseLayer(props.isActiveGroupA, displayid);
    }


    //某个图层单元格编辑渲染方案按钮被点击
    const onLayerCellEditStyleClickedCallback = function (displayid) {
        props.onLayerCellEditStyleClickedCallback(displayid);
    }

    return (
        <>

            {
                (isHidePanel)?(
            <FontAwesomeIcon
                icon={faChevronRight} color="rgb(53, 151, 209)"
                style={{ position: 'absolute', left: '4px', top: '89px', fontSize: '20px',cursor:'pointer' }}
                onClick={() => setIsHidePanel(false)}
            />
            ):(
            <div className="LayersManagePanel">
                <div className="LayersManagePanelLogo">
                    <img src="./images/project-logo.png" />
                </div>
                <div className="LayersManagePanelHeader1">
                    <div className="TabBox">
                        <img src='./images/layerB.png' />
                        图层
                    </div>
                    <FontAwesomeIcon
                        icon={faChevronLeft} color="rgb(53, 151, 209)"
                        style={{ position: 'absolute', right: '4px', top: '12px', fontSize: '20px',cursor:'pointer' }}
                        onClick={() => setIsHidePanel(true)}
                    />
                </div>

                {
                    isCompare ? (
                        <div className="LayersManagePanelTabAB">
                            <div className={props.isActiveGroupA ? "LayersManagePanelTabNameActive" : "LayersManagePanelTabNameDeactive"} onClick={onGroupAClicked}>A</div>
                            <div className={props.isActiveGroupA ? "LayersManagePanelTabNameDeactive" : "LayersManagePanelTabNameActive"} onClick={onGroupBClicked}>B</div>
                            <div className="LayersManagePanelTabNameClear"></div>
                        </div>
                    ) : ""
                }

                <div className="LayersManagePanelLayersContainer">
                    <DragDropContext onDragEnd={onDragEndCallback}>
                        <Droppable droppableId="droppable">
                            {
                                (provided, snapshot) => (
                                    <div {...provided.droppableProps} ref={provided.innerRef} >
                                        {
                                            //currentGroup.slice(0).reverse().
                                            tempOrderedArr.map((lyrParams, index) => (
                                                <Draggable key={lyrParams.displayid}
                                                    draggableId={lyrParams.displayid}
                                                    index={index} >
                                                    {
                                                        (provided, snapshot) => (
                                                            <div
                                                                ref={provided.innerRef}
                                                                {...provided.draggableProps}
                                                                {...provided.dragHandleProps}
                                                                key={lyrParams.displayid}
                                                            >
                                                                <LayerCellGeneral
                                                                    lyrParams={lyrParams}
                                                                    appDateA={props.appDateA}
                                                                    appDateB={props.appDateB}
                                                                    isGroupA={props.isActiveGroupA}
                                                                    onToggleLayerVisible={onLayerCellToggleLayerVisibleCallback}
                                                                    onCloseButtonClicked={onLayerCellCloseButtonClickedCallback}
                                                                    onLayerCellEditStyleClickedCallback={onLayerCellEditStyleClickedCallback}
                                                                    onLayerCellSDUIClickedCallback={props.onLayerCellSDUIClickedCallback}
                                                                    onLayerCellExportClick={props.onLayerCellExportClick}
                                                                    onLayerCellStatisticClick={props.onLayerCellStatisticClick}
                                                                    onLayerCellCompositeClick={props.onLayerCellCompositeClick}
                                                                    onLayerCellSerialClick={props.onLayerCellSerialClick}
                                                                    onLayerCellScriptClick={props.onLayerCellScriptClick}
                                                                    onLayerCellGotsClick={props.onLayerCellGotsClick}
                                                                    onLayerCellOmcClick={props.onLayerCellOmcClick}
                                                                />
                                                            </div>
                                                        )
                                                    }
                                                </Draggable>
                                            ))
                                        }
                                    </div>
                                )
                            }
                        </Droppable>
                    </DragDropContext>
                </div>

                <img src='./images/layerpanel-add.png' onClick={onAddLayerClicked} />
                {(isCompare) ? <img src='./images/layerpanel-stopcompare.png' onClick={onStopCompareClicked} />
                    : <img src='./images/layerpanel-startcompare.png' onClick={onStartCompareClicked} />}
            </div>
            )
        }
        </>

    )
}

export default LayersManagePanel
